package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 该类是对所有的控制器增强的
 */
@ControllerAdvice
public class MyControllerAdvice {

    /**
     * @ExceptionHandler 当前方法用于捕获某种异常(包括子类)
     * 先匹配小的再匹配大的
     */
    @ExceptionHandler(Exception.class)
    public String handler(Exception e, HandlerMethod method, HttpServletResponse response) {
        e.printStackTrace();
        System.out.println("----------出现异常------------");
        //判断原本的方法是否有贴ResponseBody
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            //判断当前请求是否阿贾克斯,看出异常的方法有没有贴ResponseBody标签
            try {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(JSON.toJSONString(
                        new JsonResult(false,"系统异常请联系管理员")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }
        return "common/error";//返回到错误页面的视图
    }

    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult handlerLogicException(LogicException e){
        return new JsonResult(false,e.getMessage());
    }


}
